'use client'

import type React from 'react'

import type { AIModel } from '@/components/model-selector'
import { Download, FileJson, Image, ImageIcon, Layers, Loader2, Maximize2, Type, Upload, ZoomIn, ZoomOut } from 'lucide-react'
import { useEffect, useRef, useState } from 'react'
import ImageUpload from '@/components/image-upload'
import LayerEditor from '@/components/layer-editor'
import LayersList from '@/components/layers-list'
import ModelSelector from '@/components/model-selector'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'
import { Label } from '@/components/ui/label'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Textarea } from '@/components/ui/textarea'
import { Toggle } from '@/components/ui/toggle'

export interface Layer {
  id: string
  type: 'text' | 'image' | 'shape'
  content: string
  position?: { x: number, y: number, width: number, height: number }
  imageData?: string // Base64 image data for image layers
  style?: {
    // Text properties
    fontSize?: string
    fontFamily?: string
    fontWeight?: string
    fontStyle?: string
    lineHeight?: string
    letterSpacing?: string
    textAlign?: string
    textDecoration?: string
    color?: string

    // Background and border
    backgroundColor?: string
    borderColor?: string
    borderWidth?: string
    borderRadius?: string

    // Shadow and effects
    boxShadow?: string
    textShadow?: string
    opacity?: string

    // Layout
    padding?: string
    margin?: string
    rotation?: string

    // Image-specific style properties
    filter?: string // CSS filters for images (brightness, contrast, etc.)
    objectFit?: string // How image should fit in its bounds
  }
  // Additional metadata
  metadata?: {
    confidence?: number
    language?: string
    estimatedFont?: string
    imageType?: string
  }
}

export default function ImageAnalyzer() {
  const [uploadedImage, setUploadedImage] = useState<string | null>(null)
  const [isAnalyzing, setIsAnalyzing] = useState(false)
  const [layers, setLayers] = useState<Layer[]>([])
  const [selectedLayer, setSelectedLayer] = useState<Layer | null>(null)
  const [imageDimensions, setImageDimensions] = useState<{ width: number, height: number } | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [selectedModel, setSelectedModel] = useState<AIModel>('google/gemini-2.5-flash-image')

  // New states for JSON input mode and zoom
  const [inputMode, setInputMode] = useState<'image' | 'json'>('image')
  const [jsonInput, setJsonInput] = useState<string>('')
  const [jsonError, setJsonError] = useState<string | null>(null)
  const [scale, setScale] = useState(1)
  const [canvasBackgroundColor, setCanvasBackgroundColor] = useState('#ffffff')

  const canvasRef = useRef<HTMLCanvasElement>(null)
  const imageRef = useRef<HTMLImageElement>(null)
  const containerRef = useRef<HTMLDivElement>(null)
  const [isDragging, setIsDragging] = useState(false)
  const [dragStart, setDragStart] = useState({ x: 0, y: 0 })
  const [isResizing, setIsResizing] = useState(false)
  const [resizeHandle, setResizeHandle] = useState<string | null>(null)

  const handleImageUpload = async (imageData: string, model?: AIModel) => {
    const modelToUse = model || selectedModel

    setUploadedImage(imageData)
    setIsAnalyzing(true)
    setLayers([])
    setSelectedLayer(null)
    setError(null)

    const img = new window.Image()
    img.crossOrigin = 'anonymous'
    img.onload = () => {
      setImageDimensions({ width: img.naturalWidth, height: img.naturalHeight })
    }
    img.src = imageData

    try {
      console.log('[v0] Sending image to API for analysis with model:', modelToUse)
      const response = await fetch('/api/analyze-image', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ image: imageData, model: modelToUse }),
      })

      console.log('[v0] API response status:', response.status)
      const data = await response.json()
      console.log('[v0] API response data:', data)

      if (!response.ok) {
        throw new Error(data.details || data.error || 'Analysis failed')
      }

      const layersWithImages = await Promise.all(
        (data.layers || []).map(async (layer: Layer) => {
          if (layer.type === 'image' && layer.position) {
            const extractedImage = await extractImageRegion(
              imageData,
              layer.position.x,
              layer.position.y,
              layer.position.width,
              layer.position.height,
            )
            return { ...layer, imageData: extractedImage }
          }
          return layer
        }),
      )

      setLayers(layersWithImages)
      console.log('[v0] Set layers with extracted images:', layersWithImages.length)
    }
    catch (error: any) {
      console.error('[v0] Error analyzing image:', error)
      setError(error.message || 'Failed to analyze image. Please try again.')
    }
    finally {
      setIsAnalyzing(false)
    }
  }

  const extractImageRegion = (
    imageSrc: string,
    x: number,
    y: number,
    width: number,
    height: number,
  ): Promise<string> => {
    return new Promise((resolve) => {
      const img = new window.Image()
      img.crossOrigin = 'anonymous'
      img.onload = () => {
        const canvas = document.createElement('canvas')
        canvas.width = width
        canvas.height = height
        const ctx = canvas.getContext('2d')
        if (ctx) {
          ctx.drawImage(img, x, y, width, height, 0, 0, width, height)
          resolve(canvas.toDataURL())
        }
        else {
          resolve('')
        }
      }
      img.src = imageSrc
    })
  }

  const handleLayerUpdate = (updatedLayer: Layer) => {
    setLayers(layers.map(layer => (layer.id === updatedLayer.id ? updatedLayer : layer)))
    setSelectedLayer(updatedLayer)
  }

  const handleLayerDelete = (layerId: string) => {
    setLayers(layers.filter(layer => layer.id !== layerId))
    if (selectedLayer?.id === layerId) {
      setSelectedLayer(null)
    }
  }

  const handleLayerSelect = (layer: Layer) => {
    setSelectedLayer(layer)
  }

  const handleModelChange = (model: AIModel) => {
    setSelectedModel(model)
    if (uploadedImage) {
      handleImageUpload(uploadedImage, model)
    }
  }

  // Handle JSON input parsing and preview
  const handleJsonParse = () => {
    try {
      setJsonError(null)
      const parsedData = JSON.parse(jsonInput)

      // Validate the JSON structure
      if (!parsedData.layers || !Array.isArray(parsedData.layers)) {
        throw new Error('JSON 必须包含 \'layers\' 数组')
      }

      // Set dimensions if provided, otherwise use default
      if (parsedData.dimensions) {
        setImageDimensions({
          width: parsedData.dimensions.width || 800,
          height: parsedData.dimensions.height || 600,
        })
      }
      else {
        setImageDimensions({ width: 800, height: 600 })
      }

      // Set background color if provided
      if (parsedData.backgroundColor) {
        setCanvasBackgroundColor(parsedData.backgroundColor)
      }

      // Set layers with proper IDs
      const layersWithIds = parsedData.layers.map((layer: any, index: number) => ({
        ...layer,
        id: layer.id || `layer-${index}-${Date.now()}`,
      }))

      setLayers(layersWithIds)
      setUploadedImage(null) // Clear any uploaded image
    }
    catch (error: any) {
      setJsonError(error.message || 'JSON 解析失败')
    }
  }

  // Zoom functions
  const handleZoomIn = () => {
    setScale(prevScale => Math.min(prevScale + 0.1, 3))
  }

  const handleZoomOut = () => {
    setScale(prevScale => Math.max(prevScale - 0.1, 0.1))
  }

  const handleZoomFit = () => {
    if (!containerRef.current || !imageDimensions)
      return

    const container = containerRef.current
    const containerWidth = container.clientWidth
    const containerHeight = container.clientHeight

    const scaleX = containerWidth / imageDimensions.width
    const scaleY = containerHeight / imageDimensions.height

    // Use the smaller scale to ensure the entire image fits
    const fitScale = Math.min(scaleX, scaleY, 1) * 0.9 // 0.9 for some padding
    setScale(fitScale)
  }

  // Auto-fit when dimensions change (for JSON input mode)
  useEffect(() => {
    if (imageDimensions && containerRef.current && inputMode === 'json') {
      // Small delay to ensure container is rendered
      setTimeout(() => {
        handleZoomFit()
      }, 100)
    }
  }, [imageDimensions, inputMode])

  useEffect(() => {
    if (!canvasRef.current || !imageRef.current || !imageDimensions)
      return

    const canvas = canvasRef.current
    const ctx = canvas.getContext('2d')
    if (!ctx)
      return

    canvas.width = imageDimensions.width
    canvas.height = imageDimensions.height

    ctx.clearRect(0, 0, canvas.width, canvas.height)

    // Fill background color if in JSON mode
    if (inputMode === 'json' && !uploadedImage) {
      ctx.fillStyle = canvasBackgroundColor
      ctx.fillRect(0, 0, canvas.width, canvas.height)
    }

    layers.forEach((layer) => {
      if (!layer.position)
        return

      const { x, y, width, height } = layer.position

      if (layer.style?.backgroundColor) {
        ctx.fillStyle = layer.style.backgroundColor
        ctx.globalAlpha = Number.parseFloat(layer.style.opacity || '1')
        if (layer.style.borderRadius) {
          const radius = Number.parseInt(layer.style.borderRadius)
          ctx.beginPath()
          ctx.roundRect(x, y, width, height, radius)
          ctx.fill()
        }
        else {
          ctx.fillRect(x, y, width, height)
        }
        ctx.globalAlpha = 1
      }

      if (layer.type === 'text') {
        ctx.fillStyle = layer.style?.color || '#000000'
        ctx.font = `${layer.style?.fontStyle || 'normal'} ${layer.style?.fontWeight || '400'} ${layer.style?.fontSize || '16px'} ${layer.style?.fontFamily || 'sans-serif'}`
        ctx.textAlign = (layer.style?.textAlign as CanvasTextAlign) || 'left'
        ctx.globalAlpha = Number.parseFloat(layer.style?.opacity || '1')

        const lines = layer.content.split('\n')
        const lineHeight
          = Number.parseInt(layer.style?.fontSize || '16') * Number.parseFloat(layer.style?.lineHeight || '1.2')
        lines.forEach((line, index) => {
          let textX = x
          if (ctx.textAlign === 'center')
            textX = x + width / 2
          if (ctx.textAlign === 'right')
            textX = x + width
          ctx.fillText(line, textX, y + lineHeight * (index + 1))
        })
        ctx.globalAlpha = 1
      }

      if (layer.type === 'image' && layer.imageData) {
        const img = new window.Image()
        img.crossOrigin = 'anonymous'
        img.onload = () => {
          ctx.save()
          ctx.globalAlpha = Number.parseFloat(layer.style?.opacity || '1')

          if (layer.style?.filter) {
            ctx.filter = layer.style.filter
          }

          ctx.drawImage(img, x, y, width, height)

          ctx.filter = 'none'
          ctx.globalAlpha = 1
          ctx.restore()
        }
        img.src = layer.imageData
      }
    })
  }, [layers, imageDimensions])

  const handleMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {
    if (!selectedLayer || !imageDimensions)
      return

    const rect = e.currentTarget.getBoundingClientRect()
    const actualWidth = imageDimensions.width * scale
    const actualHeight = imageDimensions.height * scale
    const scaleX = imageDimensions.width / actualWidth
    const scaleY = imageDimensions.height / actualHeight
    const mouseX = (e.clientX - rect.left) * scaleX
    const mouseY = (e.clientY - rect.top) * scaleY

    if (selectedLayer.position) {
      const { x, y, width, height } = selectedLayer.position

      const handleSize = 10
      if (Math.abs(mouseX - (x + width)) < handleSize && Math.abs(mouseY - (y + height)) < handleSize) {
        setIsResizing(true)
        setResizeHandle('se')
        setDragStart({ x: mouseX, y: mouseY })
        return
      }

      if (mouseX >= x && mouseX <= x + width && mouseY >= y && mouseY <= y + height) {
        setIsDragging(true)
        setDragStart({ x: mouseX - x, y: mouseY - y })
      }
    }
  }

  const handleMouseMove = (e: React.MouseEvent<HTMLDivElement>) => {
    if (!selectedLayer || !imageDimensions)
      return
    if (!isDragging && !isResizing)
      return

    const rect = e.currentTarget.getBoundingClientRect()
    const actualWidth = imageDimensions.width * scale
    const actualHeight = imageDimensions.height * scale
    const scaleX = imageDimensions.width / actualWidth
    const scaleY = imageDimensions.height / actualHeight
    const mouseX = (e.clientX - rect.left) * scaleX
    const mouseY = (e.clientY - rect.top) * scaleY

    if (isDragging && selectedLayer.position) {
      const newX = Math.max(0, Math.min(mouseX - dragStart.x, imageDimensions.width - selectedLayer.position.width))
      const newY = Math.max(0, Math.min(mouseY - dragStart.y, imageDimensions.height - selectedLayer.position.height))

      const updatedLayer = {
        ...selectedLayer,
        position: {
          ...selectedLayer.position,
          x: Math.round(newX),
          y: Math.round(newY),
        },
      }
      handleLayerUpdate(updatedLayer)
    }

    if (isResizing && selectedLayer.position && resizeHandle === 'se') {
      const newWidth = Math.max(20, mouseX - selectedLayer.position.x)
      const newHeight = Math.max(20, mouseY - selectedLayer.position.y)

      const updatedLayer = {
        ...selectedLayer,
        position: {
          ...selectedLayer.position,
          width: Math.round(newWidth),
          height: Math.round(newHeight),
        },
      }
      handleLayerUpdate(updatedLayer)
    }
  }

  const handleMouseUp = () => {
    setIsDragging(false)
    setIsResizing(false)
    setResizeHandle(null)
  }

  const handleExport = () => {
    if (!canvasRef.current)
      return

    const exportCanvas = document.createElement('canvas')
    const ctx = exportCanvas.getContext('2d')
    if (!ctx || !imageDimensions)
      return

    exportCanvas.width = imageDimensions.width
    exportCanvas.height = imageDimensions.height

    // If there's an uploaded image, draw it first
    if (imageRef.current && uploadedImage) {
      ctx.drawImage(imageRef.current, 0, 0)
    }
    else if (inputMode === 'json') {
      // For JSON mode, fill with background color
      ctx.fillStyle = canvasBackgroundColor
      ctx.fillRect(0, 0, exportCanvas.width, exportCanvas.height)
    }

    // Draw the layers canvas on top
    ctx.drawImage(canvasRef.current, 0, 0)

    exportCanvas.toBlob((blob) => {
      if (!blob)
        return
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `edited-image-${Date.now()}.png`
      a.click()
      URL.revokeObjectURL(url)
    })
  }

  // Example JSON structure
  const exampleJson = JSON.stringify({
    dimensions: { width: 800, height: 600 },
    backgroundColor: '#f0f0f0',
    layers: [
      {
        id: 'text-1',
        type: 'text',
        content: 'Hello World',
        position: { x: 100, y: 100, width: 200, height: 50 },
        style: {
          fontSize: '24px',
          color: '#333333',
          fontFamily: 'Arial',
        },
      },
      {
        id: 'shape-1',
        type: 'shape',
        content: 'rectangle',
        position: { x: 300, y: 200, width: 150, height: 100 },
        style: {
          backgroundColor: '#4CAF50',
          borderRadius: '8px',
        },
      },
    ],
  }, null, 2)

  return (
    <div className="grid lg:grid-cols-[1fr_400px] gap-6">
      {/* Main Canvas Area */}
      <div className="space-y-4">
        {/* Mode Toggle */}
        <Card className="p-4">
          <div className="flex items-center justify-between">
            <Label className="text-sm font-medium">选择输入模式</Label>
            <div className="flex gap-2">
              <Toggle
                pressed={inputMode === 'image'}
                onPressedChange={() => setInputMode('image')}
                className="data-[state=on]:bg-primary"
              >
                <Image className="h-4 w-4 mr-2" />
                图片上传
              </Toggle>
              <Toggle
                pressed={inputMode === 'json'}
                onPressedChange={() => setInputMode('json')}
                className="data-[state=on]:bg-primary"
              >
                <FileJson className="h-4 w-4 mr-2" />
                JSON 输入
              </Toggle>
            </div>
          </div>
        </Card>

        {inputMode === 'image' && !uploadedImage ? (
          <ImageUpload onImageUpload={handleImageUpload} />
        ) : inputMode === 'json' && layers.length === 0 ? (
          <Card className="p-6">
            <div className="space-y-4">
              <div>
                <Label htmlFor="json-input" className="text-sm font-medium mb-2 block">
                  输入 JSON 数据
                </Label>
                <Textarea
                  id="json-input"
                  value={jsonInput}
                  onChange={e => setJsonInput(e.target.value)}
                  placeholder="输入 JSON 数据或使用下方的示例"
                  className="h-64 font-mono text-sm"
                />
              </div>

              {jsonError && (
                <Alert variant="destructive">
                  <AlertDescription>{jsonError}</AlertDescription>
                </Alert>
              )}

              <div className="flex gap-2">
                <Button onClick={handleJsonParse} className="flex-1">
                  <FileJson className="h-4 w-4 mr-2" />
                  解析 JSON
                </Button>
                <Button
                  variant="outline"
                  onClick={() => setJsonInput(exampleJson)}
                  className="flex-1"
                >
                  使用示例
                </Button>
              </div>

              <div className="text-xs text-muted-foreground space-y-1">
                <p>支持的属性：</p>
                <ul className="list-disc list-inside space-y-1 ml-2">
                  <li>dimensions: 画布尺寸 (width, height)</li>
                  <li>backgroundColor: 背景颜色</li>
                  <li>layers: 图层数组，每个图层包含 type, content, position, style 等</li>
                </ul>
              </div>
            </div>
          </Card>
        ) : (
          <Card className="relative overflow-hidden bg-card">
            {/* Zoom Controls */}
            <div className="absolute top-4 right-4 z-10 flex gap-2 bg-background/80 backdrop-blur-sm rounded-lg p-2 border">
              <Button
                size="icon"
                variant="ghost"
                onClick={handleZoomOut}
                disabled={scale <= 0.1}
                className="h-8 w-8"
              >
                <ZoomOut className="h-4 w-4" />
              </Button>
              <Button
                size="icon"
                variant="ghost"
                onClick={handleZoomFit}
                className="h-8 w-8"
              >
                <Maximize2 className="h-4 w-4" />
              </Button>
              <Button
                size="icon"
                variant="ghost"
                onClick={handleZoomIn}
                disabled={scale >= 3}
                className="h-8 w-8"
              >
                <ZoomIn className="h-4 w-4" />
              </Button>
              <div className="flex items-center px-2 text-sm font-medium">
                {Math.round(scale * 100)}
                %
              </div>
            </div>

            <div
              ref={containerRef}
              className="relative bg-muted/30 flex items-center justify-center overflow-auto"
              style={{
                minHeight: '500px',
                maxHeight: '80vh',
              }}
            >
              <div
                className="relative m-4"
                style={{
                  transform: `scale(${scale})`,
                  transformOrigin: 'center',
                  width: imageDimensions?.width || 'auto',
                  height: imageDimensions?.height || 'auto',
                }}
                onMouseDown={handleMouseDown}
                onMouseMove={handleMouseMove}
                onMouseUp={handleMouseUp}
                onMouseLeave={handleMouseUp}
              >
                {uploadedImage
                  ? (
                      <img
                        ref={imageRef}
                        src={uploadedImage}
                        alt="Uploaded"
                        className="block"
                        style={{
                          width: imageDimensions?.width || 'auto',
                          height: imageDimensions?.height || 'auto',
                        }}
                        id="analyzed-image"
                      />
                    )
                  : (
                      <div
                        ref={imageRef as any}
                        style={{
                          width: imageDimensions?.width || 800,
                          height: imageDimensions?.height || 600,
                          backgroundColor: canvasBackgroundColor,
                        }}
                      />
                    )}
                <canvas
                  ref={canvasRef}
                  className="absolute top-0 left-0 pointer-events-none"
                  style={{
                    imageRendering: 'crisp-edges',
                    width: imageDimensions?.width || 'auto',
                    height: imageDimensions?.height || 'auto',
                  }}
                />
                {selectedLayer && selectedLayer.position && imageDimensions && (
                  <div
                    className="absolute border-2 border-accent bg-accent/10 transition-all duration-200"
                    style={{
                      left: `${selectedLayer.position.x}px`,
                      top: `${selectedLayer.position.y}px`,
                      width: `${selectedLayer.position.width}px`,
                      height: `${selectedLayer.position.height}px`,
                      cursor: isDragging ? 'grabbing' : 'grab',
                    }}
                  >
                    <div
                      className="absolute -top-6 left-0 bg-accent text-accent-foreground text-xs px-2 py-1 rounded whitespace-nowrap"
                      style={{ transform: `scale(${1 / scale})`, transformOrigin: 'bottom left' }}
                    >
                      {selectedLayer.type}
                      {' '}
                      layer
                    </div>
                    <div
                      className="absolute -bottom-1 -right-1 w-3 h-3 bg-accent border-2 border-background rounded-full cursor-se-resize"
                      style={{
                        pointerEvents: 'auto',
                        transform: `scale(${1 / scale})`,
                        transformOrigin: 'center',
                      }}
                    />
                  </div>
                )}
              </div>
              {isAnalyzing && (
                <div className="absolute inset-0 bg-background/80 backdrop-blur-sm flex items-center justify-center">
                  <div className="text-center space-y-3">
                    <Loader2 className="h-8 w-8 animate-spin mx-auto text-primary" />
                    <p className="text-sm font-medium text-foreground">正在分析图层...</p>
                  </div>
                </div>
              )}
              {error && !isAnalyzing && (
                <div className="absolute inset-0 bg-background/80 backdrop-blur-sm flex items-center justify-center">
                  <div className="text-center space-y-3 max-w-md p-6">
                    <div className="h-12 w-12 rounded-full bg-destructive/10 flex items-center justify-center mx-auto">
                      <span className="text-2xl">⚠️</span>
                    </div>
                    <p className="text-sm font-medium text-foreground">分析错误</p>
                    <p className="text-xs text-muted-foreground">{error}</p>
                    <Button
                      size="sm"
                      onClick={() => {
                        setError(null)
                        if (uploadedImage)
                          handleImageUpload(uploadedImage)
                      }}
                    >
                      重试
                    </Button>
                  </div>
                </div>
              )}
            </div>
            <div className="p-4 border-t border-border bg-card flex gap-2">
              <Button
                variant="outline"
                size="sm"
                onClick={() => {
                  setUploadedImage(null)
                  setLayers([])
                  setSelectedLayer(null)
                  setImageDimensions(null)
                  setError(null)
                  setScale(1)
                  setJsonInput('')
                  setJsonError(null)
                }}
              >
                <Upload className="h-4 w-4 mr-2" />
                {inputMode === 'image' ? '上传新图片' : '重新输入'}
              </Button>
              {layers.length > 0 && (
                <Button variant="default" size="sm" onClick={handleExport}>
                  <Download className="h-4 w-4 mr-2" />
                  导出图片
                </Button>
              )}
            </div>
          </Card>
        )}

        {layers.length > 0 && !isAnalyzing && (
          <Card className="p-6 bg-card">
            <h3 className="text-lg font-semibold mb-4 flex items-center gap-2 text-foreground">
              <Layers className="h-5 w-5 text-primary" />
              分析结果
            </h3>
            <div className="grid sm:grid-cols-3 gap-4">
              <div className="p-4 rounded-lg bg-secondary/50 border border-border">
                <div className="flex items-center gap-2 mb-2">
                  <Type className="h-4 w-4 text-accent" />
                  <span className="text-sm font-medium text-secondary-foreground">文本图层</span>
                </div>
                <p className="text-2xl font-bold text-foreground">{layers.filter(l => l.type === 'text').length}</p>
              </div>
              <div className="p-4 rounded-lg bg-secondary/50 border border-border">
                <div className="flex items-center gap-2 mb-2">
                  <ImageIcon className="h-4 w-4 text-accent" />
                  <span className="text-sm font-medium text-secondary-foreground">图片元素</span>
                </div>
                <p className="text-2xl font-bold text-foreground">{layers.filter(l => l.type === 'image').length}</p>
              </div>
              <div className="p-4 rounded-lg bg-secondary/50 border border-border">
                <div className="flex items-center gap-2 mb-2">
                  <Layers className="h-4 w-4 text-accent" />
                  <span className="text-sm font-medium text-secondary-foreground">总图层数</span>
                </div>
                <p className="text-2xl font-bold text-foreground">{layers.length}</p>
              </div>
            </div>
          </Card>
        )}
      </div>

      {/* Sidebar */}
      <div className="space-y-4">
        {layers.length > 0 && (
          <Card className="bg-card">
            <Tabs defaultValue="layers" className="w-full">
              <TabsList className="w-full grid grid-cols-2 bg-muted">
                <TabsTrigger value="layers">图层列表</TabsTrigger>
                <TabsTrigger value="edit" disabled={!selectedLayer}>
                  编辑
                </TabsTrigger>
              </TabsList>
              <TabsContent value="layers" className="p-4">
                <LayersList
                  layers={layers}
                  selectedLayer={selectedLayer}
                  onLayerSelect={handleLayerSelect}
                  onLayerDelete={handleLayerDelete}
                />
              </TabsContent>
              <TabsContent value="edit" className="p-4">
                {selectedLayer && <LayerEditor layer={selectedLayer} onLayerUpdate={handleLayerUpdate} />}
              </TabsContent>
            </Tabs>
          </Card>
        )}
      </div>
    </div>
  )
}
